﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DMSkin.Controls;
using X_Code.service;


namespace X_Code
{

    //Empty 空旷的
    public partial class ShowForm : DMSkin.DMSkinForm
    {
        /// <summary>
        /// 正常登录
        /// </summary>
        public static int NORMAL_INFO=1;
        /// <summary>
        /// 回答问题登录
        /// </summary>
        public static int  DANGER_INFO = -1;
       


        private OneForm oneForm = null; //展示oneForm

        private int InfoType = 0; //首次进入显示信息类型
        private Form loginForm=null;//登录form   
        public Owner ownerInfo=null;//用户信息
        private List<CodeItem> codeData=null;//存放密码项数据
        CodeItemService cis = new CodeItemService();


        public ShowForm()
        {
            InitializeComponent();
        }
        public ShowForm(LoginForm login,int InfoType)
        {
            loginForm = login;
            this.ownerInfo = login.ownerInfo;
            this.InfoType = InfoType;
            InitializeComponent();
        }

        private void ShowForm_Load(object sender, EventArgs e)
        {
            this.Text = "[X-Code]:" + ownerInfo.Name;
            //透明度
            this.Opacity = ownerInfo.FormOpacity;
            //窗口阴影
            this.DM_Shadow = ownerInfo.IsShowShadow;
            if (ownerInfo.IsShowAnimate)
            {
                Animate.AnimateWindow(this.Handle, 300, Animate.AW_BLEND);//淡入
            }            
            //加载并显示密码数据
            InitAndShowData(null);
            //显示首次进入信息
            ShowFirstInfo();
            //用户名是否需要显示
            this.showNameLabel();    
        }

        private void ShowForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (ownerInfo == null || ownerInfo.IsShowAnimate)
            { 
                Animate.AnimateWindow(this.Handle, 300, Animate.AW_HIDE + Animate.AW_VER_NEGATIVE);//滑动退出
            }
            if (loginForm != null)
            {       //LoginForm属于主窗口,程序完全退出要先关了LoginForm
                loginForm.Close();
            }

        }
        private String nowKey = null; //表示当前选择的item携带的key

        private void codeControl1_ItemClick(object sender, EventArgs e)
        {
            
            MouseEventArgs me = (MouseEventArgs)e;
            if (sender is BodyItem)
            {
                //将item携带的key传给form
                nowKey=((BodyItem)sender).Key;
                //判断鼠标按键
                if (me.Button == MouseButtons.Left)//左键
                {
                    //MessageBox.Show("单击" + ((BodyItem)sender).ID);
                    //如果是用MessageBox。单击双击 同时打开，。只能 完成单击事件。因为阻塞了
                    //打开密码展示窗体,传入密码项
                    showOne();

                 }
                else if (me.Button == MouseButtons.Right)//右键
                {
                    itemContextMenuStrip.Show(Control.MousePosition);                  
                }
              
            }
            if (sender is DMSkin.DMControlFileItem)
            {
                 MessageBox.Show("单击" + ((DMSkin.DMControlFileItem)sender).ID);
                //如果是用MessageBox。单击双击 同时打开，。只能 完成单击事件。因为阻塞了
            }
           

        }
        private void 查看ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //展示
            showOne();
        }
        //删除项
        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrWhiteSpace(nowKey))
            {
                showInfo(MineInfo.警告, "错误:参数不合法...");
                return;
            }
            //询问是否真的删除
            DialogResult result = DMSkin.MetroMessageBox.Show(this, "确认删除 ?_?", "警告！", MessageBoxButtons.OKCancel, MessageBoxIcon.Error, 100);
            if (result == DialogResult.OK)
            {
               try
                {
                    if (cis.Del(nowKey))
                    {
                        showInfo(MineInfo.首要, "删除成功！");
                    }
                    else
                    {
                        showInfo(MineInfo.危险, "删除失败！");
                    }
                }
               catch(Exception ex)
               {
                   showInfo(MineInfo.危险, "异常："+ex.Message);
               }
            }
            //刷新操作 
            InitAndShowData(null);
            nowKey = null;
        }
        private void searchTextBox_Enter(object sender, EventArgs e)
        {
            if(searchTextBox.ForeColor == Color.Silver){
                searchTextBox.ForeColor = Color.Black;
                searchTextBox.Text = "";
            }
        }
        public void addDmIcon_Click(object sender, EventArgs e)
        {
            AddUpdateForm addForm = new AddUpdateForm(ownerInfo,FormType.AddForm, null);
            DialogResult result = addForm.ShowDialog(this);
            if (result == DialogResult.Yes)
            {
                if (!String.IsNullOrWhiteSpace(addForm.resultStr))
                {
                    
                //显示添加结果信息
                showInfo(addForm.resultColor, addForm.resultStr);
                addForm.Close();
                //刷新数据
                this.InitAndShowData(null);
                }
            }
            // MessageBox.Show(result.ToString());
        }
        private void 修改ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrWhiteSpace(nowKey))
            {
                showInfo(MineInfo.警告, "错误:参数不合法...");
                return;
            }
            //根据key查密码项
            CodeItem one = null;
            try
            {
                one= cis.FindOne(nowKey);
                if (one == null)
                {
                    showInfo(MineInfo.警告, "错误：非法参数！");
                    return;
                }
            }
            catch (Exception ex)
            {
                showInfo(MineInfo.危险, "异常：" + ex.Message);
                return;
            }

            AddUpdateForm updateForm = new AddUpdateForm(ownerInfo,FormType.UpdateForm, one);
            DialogResult result = updateForm.ShowDialog(this);
            if (result == DialogResult.Yes)
            {
                if (!String.IsNullOrWhiteSpace(updateForm.resultStr))
                {

                    //显示添加结果信息
                    showInfo(updateForm.resultColor, updateForm.resultStr);
                    updateForm.Close();
                    //刷新数据
                    this.InitAndShowData(null);
                }
            }
        }
        private void setDmIcon_Click(object sender, EventArgs e)
        {
           
            SetForm setForm = new SetForm(ownerInfo);
            DialogResult result = setForm.ShowDialog(this);
            if (!string.IsNullOrEmpty(setForm.msg))
            {
                showInfo(MineInfo.成功, setForm.msg);
            }
            setForm.Close();
        }
        private void dmIcon1_Click(object sender, EventArgs e)
        {
            //查询
            this.searchWithKey();
            
        }
        private void updateIcon_Click(object sender, EventArgs e)
        {
            //刷新
            this.showNameLabel();
            this.InitAndShowData(null);
            showInfo(MineInfo.信息, "刷新成功！");
        }




























        //选择是否显示用户名
        private void showNameLabel()
        {
            if (this.ownerInfo != null)
            {
                if (ownerInfo.IsShowName)//显示
                {
                    nameLabel.Text = ownerInfo.Name;
                    
                    if (ownerInfo.IsShowAnimate)
                    {
                        Animate.AnimateWindow(this.dmIcon4.Handle, 100, Animate.AW_SLIDE + Animate.AW_VER_POSITIVE);
                        Animate.AnimateWindow(this.nameLabel.Handle, 200, Animate.AW_SLIDE + Animate.AW_VER_POSITIVE);
                    }
                  
                    nameLabel.Visible = true;
                    dmIcon4.Visible = true;
                    //设置浮动提示
                    infoTip.SetToolTip(nameLabel, ownerInfo.Name);
                    infoTip.SetToolTip(dmIcon4, "用户名");
                }
                else
                {
                    nameLabel.Visible = false;
                    dmIcon4.Visible = false;
                }
            }
        }






        /// <summary>
        /// 展示指定nowKey密码项
        /// </summary>
        private void showOne(){
            if (String.IsNullOrWhiteSpace(nowKey))
            {
                showInfo(MineInfo.警告, "错误:参数不合法...");
                return;
            }
            //根据key查密码项
            CodeItem one = null;
            try
            {
                one = cis.FindOne(nowKey);
                if (one == null)
                {
                    showInfo(MineInfo.警告, "错误：非法参数！");
                    return;
                }
            }
            catch (Exception ex)
            {
                showInfo(MineInfo.危险, "异常：" + ex.Message);
                return;
            }

            //打开展示窗体

            oneForm = new OneForm(ownerInfo,one);

            if (ownerInfo.IsQuicklyClose)
            {
                //居于父窗口中间不管用了，自己计算吧
                oneForm.StartPosition = FormStartPosition.Manual;
                int x = this.Location.X + this.Width / 2 - oneForm.Width / 2;
                int y = this.Location.Y + this.Height / 2 - oneForm.Height / 2;

                oneForm.Location = new Point(x, y);

                oneForm.Show();
            }
            else
            {
                //模态方式打开
                oneForm.ShowDialog(this);
                if (!oneForm.IsDisposed)
                {
                    oneForm.Close();
                }
               
            }
            
           
        }


        public void ShowFirstInfo() {
            String msg = null;
            Color color = Color.Azure;
            switch(this.InfoType){
                case 0: 
                    break;
                case 1: msg = "登录成功 (^o^)";
                    color = MineInfo.成功;
                    break;
                case -1: msg = "请尽快修改密码 (-_-)";
                    color = MineInfo.警告;
                    break;
                case 2: msg = "记得设置新密码哦 (^_-)";
                    color = MineInfo.首要;
                    break;
                default: break;
            }

            if (msg != null)
            {
                //显示信息
                showInfo(color, msg);
            }

        }



        /// <summary>
        ///获取并展示密码项 
        /// </summary>
        private Boolean InitAndShowData(String key)
        {
            //清空items
            codeControl1.Items.Clear();
            try
            {
                codeData = cis.FindSomeByKey(key);
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
                //读取错误
            }
            if (codeData == null||codeData.Count<1) {//数据不存在
                if (key != null)
                {
                    showInfo(MineInfo.首要, "查询【 " + key + " 】结果为空 -_-!");
                }
                else
                {
                    addButton.Visible = true;
                }
                
                return false;
            }
            else//正常迭代展示
            {   
                addButton.Visible = false;
                //简单模式，逆序显示
                CodeItem one = null;
                int size=codeData.Count;
                for (int i = 0; i < size;i++ )
                {
                    BodyItem item = new BodyItem();
                    one = codeData[(size-1)-i];
                    item.Num = i + 1;
                    item.Key = one.Title;
                    item.Text = one.ShowInfo();//展示
                    codeControl1.Items.Add(item);
                }
            }

            this.Invalidate();//触发窗口重绘
            codeControl1.Focus();
            if (key != null)
            {
                showInfo(MineInfo.成功, "查询到【 " + key + " 】的" + codeData.Count + "条记录!");
            }
            else
            {
                searchTextBox.ForeColor = Color.Silver;
                searchTextBox.Text = "查找";
            }
            return true;
        }
        /// <summary>
        /// 搜索关键字
        /// </summary>
        public void searchWithKey()
        {
            //获取搜索框字符
            String key = searchTextBox.Text;
            if (searchTextBox.ForeColor == Color.Silver || String.IsNullOrWhiteSpace(key))
            {
                searchTextBox.Clear();
                searchTextBox.Focus();
                showInfo(MineInfo.警告, "尚未输入key！");
                return;
            }
            key = key.Trim();
            if (key.Length > 15)
            {
                showInfo(MineInfo.警告, "key的长度不超过15！");
                searchTextBox.Focus();
                return;
            }
            //调用带关键字的show
            InitAndShowData(key);
            
        }
        private void searchTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            //监听回车键并执行查询操作
            if (e.KeyChar == 13)//13表示回车
            {
                this.searchWithKey();
            }

        }

        static int MAX_TIMES = 3; //计时器时间
        int nowTimes = MAX_TIMES;
        //计时器方法
        private void messageTimer_Tick(object sender, EventArgs e)
        {
            if (nowTimes == MAX_TIMES)
            {
                //滑出
                Animate.AnimateWindow(this.messagelabel.Handle, 100, Animate.AW_SLIDE + Animate.AW_HOR_POSITIVE);
                messagelabel.Visible = true;
                this.Invalidate();//触发窗口重绘
            }
            if (nowTimes > 1)
            {
                nowTimes--;//自减 
            }
            else
            {
                //隐藏
                nowTimes = MAX_TIMES;
                Animate.AnimateWindow(this.messagelabel.Handle, 100, Animate.AW_HIDE + Animate.AW_SLIDE + Animate.AW_HOR_POSITIVE);//信息滑出
                this.Invalidate();//触发窗口重绘
                this.messageTimer.Stop();
            }
        }
        private void showInfo(Color infoColor,  String msg)
        {
            this.messageTimer.Stop();
            messagelabel.BackColor = infoColor;
            messagelabel.Text = msg;
            messagelabel.Visible = false;//确保先前信息的消失            
            //滑出
            Animate.AnimateWindow(this.messagelabel.Handle, 100, Animate.AW_SLIDE + Animate.AW_HOR_POSITIVE);
            messagelabel.Visible = true;

            this.messageTimer.Start();//开始计时器
        }



        private void dmIcon1_MouseEnter(object sender, EventArgs e)
        {
            //改变查询图标颜色
            dmIcon1.DM_Color = Color.OrangeRed;
        }

        private void dmIcon1_MouseLeave(object sender, EventArgs e)
        {
            //改变查询图标颜色
            dmIcon1.DM_Color = Color.DimGray;
        }

        private void setDmIcon_MouseEnter(object sender, EventArgs e)
        {
            //改变设置图标颜色
            setDmIcon.DM_Color = Color.OrangeRed;
        }

        private void setDmIcon_MouseLeave(object sender, EventArgs e)
        {
            //改变设置图标颜色
            setDmIcon.DM_Color = Color.Black;
        }
        private void addDmIcon_MouseEnter(object sender, EventArgs e)
        {
            //改变新增图标颜色
            addDmIcon.DM_Color = Color.OrangeRed;
        }
        private void addDmIcon_MouseLeave(object sender, EventArgs e)
        {
            //改变新增图标颜色
            addDmIcon.DM_Color = Color.Black;
        }
        private void updateIcon_MouseEnter(object sender, EventArgs e)
        {
            //改变刷新图标颜色
            updateIcon.DM_Color = Color.OrangeRed;
        }
        private void updateIcon_MouseLeave(object sender, EventArgs e)
        {
            //改变刷新图标颜色
            updateIcon.DM_Color = Color.Black;
        }
        private void ShowForm_Click(object sender, EventArgs e)
        {
           
            //使查找框失去焦点
            codeControl1.Focus();
        }
        private void searchTextBox_Leave(object sender, EventArgs e)
        {
            if(String.IsNullOrEmpty(searchTextBox.Text)){
                searchTextBox.ForeColor = Color.Silver;
                searchTextBox.Text = "查找";
            }
        }

        private void itemContextMenuStrip_Closed(object sender, ToolStripDropDownClosedEventArgs e)
        {
            codeControl1.Invalidate();//重新绘制密码项,感觉很浪费资源。。。不过是为了解决显示不完美而不得已这样
        }

        private void addButton_Click(object sender, EventArgs e)
        {
            addDmIcon_Click(sender, e);
        }

        private void 新增项ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.addDmIcon_Click(sender,e);
        }

        private void 用户设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.setDmIcon_Click(sender, e);
        }

        /// <summary>
        /// 监听f5 用于刷新操作
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="keyData"></param>
        /// <returns></returns>
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.F5)
            {
                searchTextBox.Clear();
                searchTextBox.ForeColor = Color.Silver;
                searchTextBox.Text = "查找";
                this.InitAndShowData(null);
                showInfo(MineInfo.信息, "刷新成功！");
                return false;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        /// <summary>
        /// 窗口成为活动控件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ShowForm_Activated(object sender, EventArgs e)
        {
            if (oneForm != null)
            {
                oneForm.Close();
            }
           
        }


        private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new AboutForm(ownerInfo).ShowDialog(this);
        }

        private void 帮助ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new DescPWForm(ownerInfo).ShowDialog(this);
        }

        private void 随机密码生成StripMenuItem_Click(object sender, EventArgs e)
        {
            new MakePWForm(ownerInfo).ShowDialog(this);
        }
    }
}
